from typing import Optional
from contextlib import redirect_stdout
from io import StringIO
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
# origins = [
#     "http://localhost:5000",
#     "http://0.0.0.0:5000",
#     "http://127.0.0.1:80",
#     "http://localhost:80",
# ]

# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=origins,
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )


class Func(BaseModel):
    code: str
    name: Optional[str] = None


@app.post("/coderun/")
async def code_run(func: Func):
    # exec code ,need to add filter to avoid unsecurity command
    # limit globals and locals variables

    f = StringIO()
    with redirect_stdout(f):
        exec(func.code)

    # return exec result
    return f.getvalue()


if __name__ == "__main__":
    uvicorn.run(app='main:app', host="localhost",
                port=5000, reload=True, workers=2)
